Page({
  data: {
    username: '',
    password: '',
    remember: false,
    loading: false
  },
  
  onLoad() {
    // 检查是否有记住的登录信息
    const savedUser = wx.getStorageSync('rememberedUser')
    if (savedUser) {
      try {
        const userData = JSON.parse(savedUser)
        this.setData({
          username: userData.username,
          remember: true
        })
      } catch (e) {
        console.error('读取保存的用户信息失败', e)
      }
    }
  },
  
  onInputChange(e) {
    const field = e.currentTarget.dataset.field
    this.setData({
      [field]: e.detail.value
    })
  },
  
  toggleRemember() {
    this.setData({
      remember: !this.data.remember
    })
  },
  
  handleLogin() {
    const { username, password, remember } = this.data
    
    if (!username) {
      wx.showToast({
        title: '请输入用户名',
        icon: 'none'
      })
      return
    }
    
    if (!password) {
      wx.showToast({
        title: '请输入密码',
        icon: 'none'
      })
      return
    }
    
    this.setData({ loading: true })
    
    // 简单的登录验证
    if ((username === 'admin' || username === 'user') && password === '1') {
      if (remember) {
        wx.setStorageSync('rememberedUser', JSON.stringify({
          username: username
        }))
      } else {
        wx.removeStorageSync('rememberedUser')
      }
      
      // 存储登录状态和角色信息
      wx.setStorageSync('isLoggedIn', true)
      wx.setStorageSync('userInfo', {
        username: username,
        role: username === 'admin' ? 'admin' : 'user'
      })
      
      // 获取全局App实例并更新状态
      const app = getApp()
      app.globalData.isLoggedIn = true
      app.globalData.userInfo = {
        username: username,
        role: username === 'admin' ? 'admin' : 'user'
      }
      
      setTimeout(() => {
        this.setData({ loading: false })
        wx.showToast({
          title: '登录成功',
          icon: 'success'
        })
        wx.switchTab({
          url: '/pages/home/home'
        })
      }, 800)
    } else {
      setTimeout(() => {
        this.setData({ loading: false })
        wx.showToast({
          title: '用户名或密码错误',
          icon: 'none'
        })
      }, 800)
    }
  }
}) 